<template>
  <div class="main">
    <div class="search">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-button type="success" size="small" @click="form = { goodsPictures: [], goodsSpecs: [], goodsCombines: [] }; dialogShow = true">添加</el-button>
        </el-form-item>
        <el-form-item label="商品货号" prop="no" class="required">
          <el-input v-model="search.no" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="search.name" size="small" placeholder="商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品类型">
          <treeselect
              style="width: 200px;"
              v-model="search.goodsTypeId"
              :multiple="false"
              :options="goodsTypeTree"
              :normalizer="(node) => {return {
                              id: node.id,
                              label: node.name,
                              children: node.children,
                            }}"
              placeholder="请选择商品类别"
          >
          </treeselect>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="search.description" size="small" placeholder="备注" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="small" @click="searchClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list">
      <el-table
          :data="data"
          stripe
          style="width: 100%">
        <el-table-column prop="cover" label="封面">
          <template slot-scope="scope">
            <el-image :src="scope.row.cover" fit="contain" style="height: 60px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" style="font-size: 60px;"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="no" label="商品货号"></el-table-column>
        <el-table-column prop="name" label="商品名称">
        </el-table-column>
        <el-table-column prop="goodsTypeId" label="商品类型">
          <template slot-scope="scope">
            {{ scope.row.goodsType ? scope.row.goodsType.name : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="商品类别">
          <template slot-scope="scope">
            {{ scope.row.type === 1 ? '批发' : '租赁' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格"></el-table-column>
        <el-table-column prop="stock" label="商品库存"></el-table-column>
        <el-table-column prop="description" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog
        :title="form.id ? '修改' : '添加'"
        :visible.sync="dialogShow"
        fullscreen
        width="600px"
        @close="dialogClose"
    >
      <el-form :model="form" ref="form" :rules="rules" label-position="left" label-width="80px" size="medium"
               @submit.native.prevent>
        <el-form-item label="货号" prop="no" class="required">
          <el-input v-model="form.no" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name" class="required">
          <el-input v-model="form.name" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price" class="required">
          <el-input-number v-model="form.price" class="full-width-input" controls-position="right"
                           :min="0" :max="1000000000" :precision="2" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock" class="required">
          <el-input-number v-model="form.stock" class="full-width-input" controls-position="right"
                           :min="0" :max="1000000000" :precision="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsTypeId" class="required">
          <treeselect
              v-model="form.goodsTypeId"
              :multiple="false"
              :options="goodsTypeTree"
              :normalizer="(node) => {return {
                              id: node.id,
                              label: node.name,
                              children: node.children,
                            }}"
              placeholder="请选择商品类型"
          >
          </treeselect>
        </el-form-item>
        <el-form-item label="商品类别" prop="type" class="required">
          <el-select v-model="form.type" placeholder="请选择商品类别">
            <el-option label="批发" value="1"></el-option>
            <el-option label="租赁" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图" prop="goodsPictures">
          <el-upload :headers="{ token: token }" :file-list="form.goodsPictures" :on-success="pictureSuccess" :on-remove="pictureRemove"
                     action="/upload/image" list-type="picture-card" show-file-list :limit="20">
            <template #default><i
                class="el-icon-plus"></i></template>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品规格" prop="goodsSpecs">
          <el-row>
            <el-col :span="1">
              <el-button type="primary" icon="el-icon-plus" circle @click="form.goodsSpecs.push({ name: '', values: [] })"></el-button>
            </el-col>
            <el-col :span="24" v-if="form.goodsSpecs.length">
              <table>
                <thead>
                <tr>
                  <th>名称</th>
                  <th>选项</th>
                  <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in form.goodsSpecs" :key="index">
                  <td><el-input v-model="item.name" type="text" clearable></el-input></td>
                  <td>
                    <el-select
                        v-model="item.values"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        placeholder="请选择规格标签">
                      <el-option
                          v-for="(v, ind) in item.values"
                          :key="ind"
                          :label="v.value"
                          :value="v.value">
                      </el-option>
                    </el-select>
                  </td>
                  <td>
                    <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="form.goodsSpecs.splice(index, 1)"></el-button>
                  </td>
                </tr>
                </tbody>
              </table>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="组合规格" prop="goodsCombines">
          <el-row>
            <el-col :span="1">
              <el-button type="primary" icon="el-icon-plus" circle @click="form.goodsCombines.push({ specsIds: [] })"></el-button>
            </el-col>
            <el-col :span="24" v-if="form.goodsCombines && form.goodsCombines.length">
              <table>
                <thead>
                <tr>
                  <th v-for="item in form.goodsSpecs" :key="item.name">{{ item.name }}</th>
                  <th>价格</th>
                  <th>库存</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(gcItem, index) in form.goodsCombines" :key="gcItem.name" >
                  <td v-for="(gsItem, i) in form.goodsSpecs" :key="gsItem.name">
                    <el-select
                        v-model="gcItem.specsIds[i]"
                        filterable
                        default-first-option
                        placeholder="请选择规格标签">
                      <el-option
                          v-for="(v, ind) in gsItem.values"
                          :key="ind"
                          :label="v"
                          :value="v">
                      </el-option>
                    </el-select>
                  </td>
                  <td>
                    <el-input-number :precision="2" v-model="gcItem.price" clearable></el-input-number>
                  </td>
                  <td>
                    <el-input-number v-model="gcItem.stock" clearable></el-input-number>
                  </td>
                  <td>
                    <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="form.goodsCombines.splice(index, 1)"></el-button>
                  </td>
                </tr>
                </tbody>
              </table>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="form.description" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="详细介绍" prop="context">
          <div style="border: 1px solid #ccc; min-height: 700px;">
            <toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                mode="default"
            />
            <editor
                style="height: 500px; overflow-y: hidden;"
                v-model="form.context"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="onCreated"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from "../util/auth";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

export default {
  name: "Goods",
  components: {Treeselect, Editor, Toolbar},
  data() {
    return {
      search: {},
      dialogShow: false,
      form: {
        goodsPictures: [],
        goodsSpecs: [],
        goodsCombines: []
      },
      data: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      rules: {
        no: [
          {
            required: true,
            message: '商品货号不能为空',
          },
          {
            min: 1,
            max: 300,
            message: '商品货号长度在1-300位之间',
            trigger: 'blur'
          }],
        name: [
          {
            required: true,
            message: '商品名称不能为空',
          },
          {
            min: 1,
            max: 300,
            message: '商品名称长度在1-300位之间',
            trigger: 'blur'
          }],
        price: [{
          required: true,
          message: '商品价格不能为空',
        }],
        stock: [{
          required: true,
          message: '商品库存不能为空',
        }],
        goodsTypeId: [{
          required: true,
          message: '商品类型不能为空',
        }],
        type: [{
          required: true,
          message: '商品类别不能为空',
        }],
        description: [
          {
            min: 0,
            max: 800,
            message: '备注长度在3-800位之间',
            trigger: 'blur'
          }
        ]
      },
      goodsTypeTree: [],
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...'
      }
    }
  },
  mounted() {
    this.$http.post(`goods-type/tree`, this.search).then(res => {
      if (res.code === 200) {
        this.goodsTypeTree = res.data
      }
    })
    this.getData()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    edit(obj) {
      this.form = {...obj};
      let specsMap = {};
      this.form.goodsSpecs.forEach(v => {
        if(specsMap[v.name]) specsMap[v.name].values.push(v.value)
        else specsMap[v.name] = { name: v.name, values: [v.value] }
      })
      this.form.goodsCombines.forEach(v => {
        v.specsIds = v.specsId.split(',')
      })
      this.form.goodsSpecs = Object.values(specsMap)
      this.dialogShow = true;
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      const uploadImage = this.editor.getMenuConfig('uploadImage')
      uploadImage.server = '/upload/image'
      uploadImage.fieldName = 'file'
      uploadImage.headers = {
        token: getToken()
      }
      uploadImage.maxFileSize = 10 * 1024 * 1024
      const uploadVideo = this.editor.getMenuConfig('uploadVideo')
      uploadVideo.server = '/upload/video'
      uploadVideo.fieldName = 'file'
      uploadVideo.headers = {
        token: getToken()
      }
      uploadVideo.maxFileSize = 500 * 1024 * 1024
    },
    getData() {
      this.$http.post(`goods/page?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.search).then(res => {
        if (res.code === 200) {
          this.pageSize = res.data.size
          this.pageNo = res.data.current
          this.total = res.data.total
          this.data = res.data.records
        }
      })
    },
    sizeChange(val) {
      this.pageNo = 1;
      this.pageSize = val;
      this.getData();
    },
    currentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    searchClick() {
      this.pageNo = 1;
      this.getData()
    },
    dialogClose() {
      this.form = {goodsPictures: [], goodsSpecs: []}
      this.$refs['form'].clearValidate()
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log(this.form)
          if (this.form.id) {
            this.$http.put(`goods`, this.form).then(res => {
              if (res.code === 200) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          } else {
            this.$http.post(`goods`, this.form).then(res => {
              if (res.code === 200) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          }
        }
      });
    },
    del(id) {
      this.$confirm('是否确认删除?删除可能会影响部分订单显示！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`goods/${id}`).then(res => {
          if (res.code === 200) {
            this.getData()
            this.$Message.success(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    pictureSuccess(result, file, fileList) {
      if (result.errno === 0) {
        this.form.goodsPictures = fileList.map(v => { return {url: v.response ? v.response.data.url: v.url} })
      }
    },
    pictureRemove(file, fileList) {
      this.form.goodsPictures = fileList.map(v => { return {url: v.url} })
    }
  },
  computed: {
    token() {
      return getToken()
    }
  }
}
</script>

<style scoped>

</style>
